---
import Form from "@/components/Form.astro";
import Button from "@/components/Button.astro";
import TextFieldInput from "@/components/TextFieldInput.astro";
import TextFieldLabel from "@/components/TextFieldLabel.astro";

import { buttonVariants } from "@/components/ui/button";
import { AUTH_API } from "@/lib/constants";
import { cn } from "@/lib/utils";

const formBaseAction = `${AUTH_API}/login`;
const BASE_URL = import.meta.env.BASE_URL;
---

<Form title="Login">
  <div>
    <form
      id="login-form"
      class="flex flex-col gap-2"
      action={`${formBaseAction}`}
      data-base_action={formBaseAction}
      data-base_url={BASE_URL}
      method="post"
      enctype="application/x-www-form-urlencoded"
    >
      <div class="hidden" set:html={`{{ state | escape("none") }}`}></div>

      <div
        class="grid grid-cols-2 items-center gap-4"
        style={{"grid-template-columns": "auto 1fr"}}
      >
        <TextFieldLabel>User:</TextFieldLabel>
        <TextFieldInput
          required
          tabindex="1"
          type="email"
          name="email"
          placeholder="Email"
          autocomplete="username"
        />

        <TextFieldLabel>Password:</TextFieldLabel>
        <TextFieldInput
          required
          tabindex="2"
          type="password"
          name="password"
          placeholder="Password"
          autocomplete="current-password"
        />
      </div>

      <div class="flex justify-center gap-1 text-sm">
        <span>Forgot your password?</span>
        <a tabindex="5" href={`${BASE_URL}/reset_password/request`} class="text-primary">Reset</a>
      </div>

      <div class="my-2 flex justify-between">
        {"{% if enable_registration -%}"}
          <a tabindex="4" type="button" href={`${BASE_URL}/register`} class:list={buttonVariants({ variant: "default" })}>
            Register
          </a>
        {"{%- endif %}"}

        <Button tabindex="3" variant="default" type="submit">
          Sign In
        </Button>
      </div>
    </form>

    {"{% if !oauth_providers.is_empty() %}"}
    <div class="mt-4 flex w-full flex-col items-start gap-4">
      <div class="flex w-full justify-center text-muted-foreground">
        Or authenticate using:
      </div>

      {"{% for provider in oauth_providers %}"}
      <a
        class={cn("w-full", buttonVariants({ variant: "outline" }))}
        href={`${AUTH_API}/oauth/{{ provider.name }}/login{{ self::render_safe_query_params(oauth_query_params) }}`}
      >
        <div class="flex items-center gap-2">
          <img class="size-[28px]" src={`${BASE_URL}/oauth2/{{ provider.img_name }}`} alt={`{{ provider.display_name }}`} />
          <span class="font-bold">{`{{ provider.display_name }}`}</span>
        </div>
      </a>
      {"{% endfor %}"}
    </div>
    {"{% endif %}"}
  </div>
</Form>
